<template>
  <div>
    <table
      border="1"
      width="700"
      style="border-collapse: collapse"
    >
      <caption>
        购物车
      </caption>
      <thead>
        <tr>
          <th>
            <input type="checkbox" @change="onChange" :checked="totalChange"/> <span>全选</span>
          </th>
          <th>名称</th>
          <th>价格</th>
          <th>数量</th>
          <th>总价</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <!-- <my-tr :myObj="item" v-for="item in myList" :key="item.name"></my-tr> -->
        <tr v-for="(item,index) in myList" :key="item.name">
          <td><input type="checkbox" :checked="item.checked" @change="onChangex(index)" ></td>
          <td>{{item.name}}</td>
          <td>{{item.price}}</td>
          <td><button @click="onSub(index)">-</button>{{item.num}}<button @click="onAdd(index)">+</button></td>
          <td>{{totalPrice(index)}}￥</td>
          <td><button @click="onDel(index)">删除</button></td>
        </tr>
      </tbody>
      <tfoot>
        <tr>
          <td>合计:</td>
          <td colspan="5">
            {{allPrice}}￥
          </td>
        </tr>
      </tfoot>
    </table>
    <div>
      <span>名称:<input v-model.trim="form.name" type="text"></span><br>
      <span>价格:<input v-model.number="form.price" type="number"></span><br>
      <span>数量:<input v-model.number="form.num" type="number"></span>
      <span><button @click="onData">添加</button></span>
    </div>
  </div>
</template>

<script>
import { mapState, mapMutations, mapGetters } from 'vuex'
import { Toast } from 'vant'
export default {
  data () {
    return {
      form: {
        name: '',
        price: '',
        num: '',
        checked: false
      }
    }
  },
  computed: {
    ...mapGetters(['totalPrice', 'totalChange', 'allPrice']),
    ...mapState({
      myList: 'goodList'
    })
  },
  created () {
  },
  methods: {
    ...mapMutations(['subNum', 'addNum', 'allChange', 'delData', 'changeX', 'addData']),
    onData () { // 数据添加
      if (this.form.name === '' || this.form.price === '' || this.form.num === '') {
        return Toast('添加数值不能有空')
      } else {
        this.addData(this.form, _ => {
          this.form.name = ''
          this.form.price = ''
          this.form.num = ''
        })
      }
    },
    onDel (index) {
      this.delData(index)
    },
    onChangex (index) {
      this.changeX(index)
    },
    onChange () {
      this.allChange(!this.totalChange)
    },
    onSub (index) {
      this.subNum(index)
    },
    onAdd (index) {
      this.addNum(index)
    }
  }
}
</script>

<style scoped lang='less'>

</style>
